/** @jsxImportSource @emotion/react */
//import { jsx, Global } from "@emotion/react";
import * as React from "react";
//import Editor, { tryValue } from "./Editor";
//import { ImageUpload } from "./ImageUpload";
//import { Image } from "./Image";
//import { Value } from "slate";
//import debug from "debug";
//import initialValue from "./value.json";
//import { Ingredient } from "./RecipeList";
import {
  Input,
  Text,
  Button,
  useTheme,
  InputBaseProps,
  useToast,
  LayerLoading,
  Container,
  Select,
  ListItem,
  Avatar,
  MenuList,
  MenuItem,
  IconPackage,
  IconButton,
  IconMoreVertical,
  List,
  InputLine,
  SuffixInput,
  ButtonRefComp,
  IconZapOff,
  IconCheckSquare,
  DdMenu,
  DdMenuItem,
  IconCheck,
  IconMenu,
  IconCloud
} from "customize-easy-ui-component";
//import { useCreateDevice, useUpdateDevice } from "./db";

//import { Link as RouterLink, useLocation } from "wouter";
import { css } from "@emotion/react";
//import { Link as RouterLink } from "wouter";
import {设备种类,设备类别,设备品种} from "./../dict/eqpComm"
//import { InspectRecordLayout, SelectHookfork } from "../report/comp/base";
import { 电梯 as ElevatorComp  } from "./edit/电梯";
import { 锅炉 as BoilerComp } from "./edit/锅炉";
import { 起重 as CraneComp } from "./edit/起重";
import { 升降机 as LifterComp } from "./edit/升降机";
import { 容器 as VesselComp } from "./edit/容器";
import { 常压容器 as VesselCompR } from "./edit/常压容器";
import { 厂车 as FactoryVehicleComp } from "./edit/厂车";
import { 游乐 as AmusementComp } from "./edit/游乐";
import { 压力管道 as PipelineComp } from "./edit/压力管道";
import { useThrottle } from "../hooks/useHelpers";
import useRegisterMutation from "../common/useRegisterMutation";
import useCreateDeviceMutation from "./useCreateDeviceMutation";
import { Link as RouterLink } from "../routing/Link";
import {useContext} from "react";
import RoutingContext from "../routing/RoutingContext";
import useRemoveDeviceMutation from "./useRemoveDeviceMutation";
import {ContainLine, TransparentInput} from "../comp/base";
import useUpdateDeviceMutation from "./useUpdateDeviceMutation";
import {DeviceClassSelect} from "./DeviceClassSelect";


interface ComposeDeviceProps {
  id?: string;
  readOnly?: boolean;
  dt?:any;    //无污染直接来自后端的Eqp台账 数据；
}

export const ComposeDevice: React.FunctionComponent<ComposeDeviceProps> = ({
  readOnly,
  id,
  dt : eqp =null,
}) => {
  const theme = useTheme();
  const toast = useToast();
 // const {user,} = useSession();
  //const [loading, setLoading] = React.useState(false);
  const [editing, ] = React.useState(!readOnly|| true);
  /* const [content, ] = React.useState(() => {
        return defaultDescription
          ? ''
          : null;
      });　 */

  //这里ingredients挂载初始化后只能setIngredients改了，useState()后面参数变动就不再起作用了。
  //const [ingredients, setIngredients] = React.useState<any>( dt||{} );

  //const [, setLocation] = useLocation();
 // const [eqpType, setEqpType] = React.useState(undefined);
  //可编辑的设备数据表 要创建新设备=null,首先生成ID,随后刷新路由再进来 eqp有基本数据了。

  //【问题啊】[eqp, setEqp] = React.useState(dt)点击同一条设备不会 更新，dt eqp实际存在差异了；除非点击其它再回来？应该改成直传eqp=dt
  //要把ComposeDevice里[eqp, setEqp] = React.useState(dt)改成eqp=dt短接驱动，避免没切换路由的情形下无感知上级dt变化。
  //const [eqp, setEqp] = React.useState(dt);    //为了更改数据用的。
  console.log("电梯组件传递zz参数来svp eqp=",eqp);

  const {history } = useContext(RoutingContext);

  //const [, setOptions] = React.useState({});
//  const {result:entry, submit:submitfunc, error} = useCreateDevice(eqp?.type,{oid:"暂且空着",  ...ingredients, ...eqp});
  const {call:createEqpfunc,isInFlight, result:entry}= useCreateDeviceMutation();
  const {call:removeEqpfunc,isInFlight:doing, result:isok}= useRemoveDeviceMutation();
  const {call:updateEqpfunc,isInFlight:saving }= useUpdateDeviceMutation();
/*
  const {result:saveres, submit:dosaveEqpfunc, error:saveerr,loading,called} = useUpdateDevice({ id, unt:4644,
    in:{...ingredients, ...eqp, __typename:undefined} });
*/
//  const {doFunc:throttledSaveEqp, ready} = useThrottle(dosaveEqpfunc,9000);
  //为了更改数据用的。
  const [cod, setCod] = React.useState<string|undefined>(eqp?.cod);
  const [oid, setOid] = React.useState<string|undefined>(eqp?.oid);
  //保存到后端服务器render次数较多的, 参考:\优化.txt
  //console.log("刚ComposeDevice经过EQPis",dt,"进行中id=",id,"eqp=",eqp);
  //不能在这点击触发函数内部执行HOOKs!! 必须上移动外移到 界面组件的头部初始化hooks，随后点击触发调用hook钩子函数。
  async function saveRecipe() {
    try {
      //setLoading(true);
      //这时才去修改submitfunc参数，已经来不及，setOptions异步执行；submitfunc会看见前面的取值。
      //setOptions({oid:"test暂且空着",  ...ingredients});

      await createEqpfunc("3",{flo:261, cod, oid});   //要等待正常的结果应答从后端返回。
      //submitfunc(); 立刻执行后面代码，这样不会等待后端应答的。
      /*点击函数发送给后端服务器，即刻返回到这里了await submitfunc();　这个时候entry还不是后端的应答数据，要等到下一次entry被ＨＯＯＫ修正*/
    //  console.log("等半天createEntry返回error=",error,"结果",entry );

      //加了await 后的　submitfunc();似乎也不能确保entry非空的，必须等待下一次render()。
  //    entry && setLocation("/device/" + entry.id, { replace: true } );
      //原型是 PushCallback = (to: Path, replace?: boolean) => void;
    } catch (err: any) {
      //setLoading(false);
      toast({
        title: "捕获errcc错",
        subtitle: err.message,
        intent: "error"
      });
      console.log("捕获err打了吗", err);
    }
  }

  /**参数eqp:回调，下一级组件修改之后的eqp台账新数据。
   * */
  async function updateDevice( eqp :any
  ) {
    try {
      //setLoading(true);
      console.log("保存设备2等待之前 输入A=", eqp );
      //这时才去修改submitfunc参数，已经来不及，setOptions异步执行；submitfunc会看见前面的取值。
      //setOptions({oid:"test暂且空着",  ...ingredients});
      //【实际上】eqp这里以从输出被转成了输入对象使用了，共享用的。有些字段是新增加是最早的输出对象eqp中不存在的。
      //const inpPreare={...ingredients,  ...eqp, ;;
      const inpPreare={ ...eqp,
        makeu: eqp.makeu?.id, owner: eqp.owner?.id, remu: eqp.remu?.id, repu: eqp.repu?.id, insu: eqp.insu?.id,
        mtu: eqp.mtu?.id, ispu: eqp.ispu?.id, useu: eqp.useu?.id, usud: eqp.usud?.id,
        nxtd1: undefined,nxtd2: undefined,isp1: undefined,isp2: undefined,pos: eqp.pos?.id,
        ad: eqp.ad?.id, vlg: eqp.vlg?.id, lat: eqp.geo?.lat, lon: eqp.geo?.lon,
        svp: JSON.stringify(eqp.svp),  pa: JSON.stringify(eqp.pa),
        vl: Number(eqp.vl),
      };
      //以下屏蔽掉不需要编辑输入的：估计输出对象直接复制过来的，输入对象不需要啊。
      const {ust,uscd,cerd,reg,rcod,rnam,regd,cand,regu,svu,usObj,mtObj,geo,__typename,
              ocat,ispud,crDate, ...inpData} =inpPreare;
      //把输出对象Eqp直接复制当成输入的经常会出错：随便增加个字段，后端接口输入接收没有相应增加就失败。并且类型必须可以匹配的{id:name:}对象转成ID;
      updateEqpfunc( id!, '4644', inpData);
      //submitfunc(); 立刻执行后面代码，这样不会等待后端应答的。uscd cert cerd
      /*点击函数发送给后端服务器，即刻返回到这里了await submitfunc();　这个时候entry还不是后端的应答数据，要等到下一次entry被ＨＯＯＫ修正*/
   //   console.log("等半天createEntry返回error=",error,"结果",saveres );
      //setLoading(false);
      //加了await 后的　submitfunc();似乎也不能确保entry非空的，必须等待下一次render()。
    //  entry && setLocation("/device/" + saveres.id, { replace: true } );
      //原型是 PushCallback = (to: Path, replace?: boolean) => void;
    } catch (err: any) {
      //setLoading(false);
      toast({
        title: "捕获errcc错",
        subtitle: err.message,
        intent: "error"
      });
      console.log("捕获err打了吗", err);
    }
  }

  //保存 编辑新的设备之后，要修正URL
  React.useEffect(() => {
    entry && ( history.push("/device/" + entry));
  }, [entry, history]);
  //点击前触发子孙组件的各个输入框onBlur()都触发干净了。
  const commitBlurRef =React.useRef<HTMLDivElement | null>(null);

  // const {save, field, reurl, p1field, multi}= window.history.state?.state??{};      //通用伪对话框传递格式
  // const dxDevs= JSON.parse(sessionStorage['设备多选集']??'[]') as any[];
  //旧方式直接用API的没有考虑同步问题，点击以后存储被修改了但是当前页面不能自动重新render不能呈现新数据，sessionStorage  localStorage

  return (
    <div
      css={{
        [theme.mediaQueries.md]: {
          height: "auto",
          display: "block"
        }
      }}
    >
      <div
        css={{
          flex: 1,
          [theme.mediaQueries.md]: {
            flex: "none"
          }
        }}
      >
        <div>
          <Container>
            <div
              css={{
                paddingTop: theme.spaces.lg,
                paddingBottom: theme.spaces.lg
              }}
            >

                <div>
                  <Text variant="h5">设备明细信息</Text>

                      <div key={1}>
                        {editing ? (
                        <div>
                          <ContainLine display={'设备号'}>
                              <TransparentInput
                                autoFocus={false}
                                placeholder="那一台电梯？"
                                value={cod || ''}
                                onChange={e => setCod( e.currentTarget.value||undefined) }
                              />
                          </ContainLine>
                          <ContainLine display={'监察识别码'}>
                            <TransparentInput
                              autoFocus={false}
                              placeholder="导入的情形可以不填写"
                              value={oid || ''}
                              onChange={e => setOid(e.currentTarget.value||undefined) }
                            />
                          </ContainLine>
                        </div>
                        ) : (
                          <div
                            css={{
                              backgroundColor: "transparent",
                              display: "flex",
                              marginLeft: "-0.25rem",
                              paddingLeft: "0.25rem",
                              marginRight: "-0.25rem",
                              paddingRight: "0.25rem",
                              marginBottom: theme.spaces.xs,
                              justifyContent: "space-between",
                              [theme.mediaQueries.md]: {
                                width: "500px"
                              }
                            }}
                          >
                            <Text
                              css={{
                                paddingRight: theme.spaces.xs,
                                backgroundColor: false
                                  ? theme.colors.palette.blue.lightest
                                  : "white"
                              }}
                            >
                              设备号：{eqp.cod}
                            </Text>
                            <div
                              css={{
                                flex: 1,
                                borderBottom: `1px dashed ${
                                  theme.colors.border.muted
                                }`,
                                marginBottom: "6px"
                              }}
                            />
                            <Text
                              css={{
                                paddingLeft: theme.spaces.xs,
                                backgroundColor: false
                                  ? theme.colors.palette.blue.lightest
                                  : "white"
                              }}
                            >
                              监察识别码：{eqp.oid}
                            </Text>
                          </div>
                        )}

                        <DeviceClassSelect  eqp={eqp} />

                        { eqp?.__typename==='Elevator' && (
                            <ElevatorComp  id={id}  readOnly={true} editable={true}  eqp={eqp} mutationFunc={updateDevice}/>
                        ) }

                        { eqp?.__typename==='Boiler' && (
                            <BoilerComp  id={id}  readOnly={true} editable={true}  eqp={eqp} mutationFunc={updateDevice}/>
                        ) }
                        { eqp?.__typename==='Crane' && (
                            eqp.sort==='48' ?
                            <LifterComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                               :
                            <CraneComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                        ) }

                        { eqp?.__typename==='Vessel' && (
                            eqp.type==='R' ?
                              <VesselCompR  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                                :
                              <VesselComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                        ) }
                        { eqp?.__typename==='FactoryVehicle' && (
                            <FactoryVehicleComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                        ) }
                        { eqp?.__typename==='Amusement' && (
                            <AmusementComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                        ) }
                        { eqp?.__typename==='Pipeline' && (
                            <PipelineComp  id={id}  readOnly={true} editable={true} eqp={eqp} mutationFunc={updateDevice}/>
                        ) }

                      </div>

                </div>


              {editing && <Button
                  intent="primary"
                  disabled={false}
                  css={{ marginLeft: theme.spaces.sm }}
                  onPress={() => {  //按钮里面看不到最新的input取值的。
                     saveRecipe();
                  }}
                  >
                生成新设备
                </Button>
              }
              <Button
                  intent="primary"
                  css={{ marginLeft: theme.spaces.sm }}
                  onPress={() => {  //按钮里面看不到最新的input取值的。
                    //TODO: 查询设备null，必须删除掉设备； 暂时固定ID
                    removeEqpfunc('RXFwOjY5');
                  }}
              >
                淘汰设备
              </Button>

        {/* @Deprecated   {editing && <ButtonRefComp
                intent="primary"
                disabled ={false}
                ref={commitBlurRef}
                css={{ marginLeft: theme.spaces.sm }}
                onPointerOver={(e :any) => {
                  //似乎没有效果啊，多套了一层,  eqp汇集状态变量二传手
                  commitBlurRef!.current!.focus();
                }}
                onPress={ async () => {
                  //无法直接获取到各个字段的编辑器组件关联的一个个的状态变量，eqp实际是经过汇集二传手的对象，所以要多出一道确认按钮程序。
                  await updateDevice({ ...eqp }  );
                } }
              >
                更新设备信息到后端服务器
              </ButtonRefComp>
              }*/}
            </div>

          </Container>
        </div>
      </div>

    </div>
  );
};

